package cn.quevo.ucenter.client;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public class ClientRestTemplate {

    private RestTemplate restTemplate;

    public ClientRestTemplate() {
        this.init();
    }

    public ClientRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
        if (this.restTemplate == null) {
            this.init();
        }
    }

    private void init() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        // 设置连接超时时间(毫秒)
        factory.setConnectTimeout(3000);
        // 设置读取超时时间(毫秒)
        factory.setReadTimeout(3000);
        this.restTemplate = new RestTemplate(factory);
    }

    public RestTemplate getRestTemplate() {
        if (this.restTemplate == null) {
            this.init();
        }
        return this.restTemplate;
    }

    /**
     * 请求
     * 
     * @author July july_sky@foxmail.com
     * @date 2018年3月28日 上午10:34:42
     * @param url
     * @param headers
     * @param responseType
     * @return
     */
    public <T> T postForObject(String url, HttpHeaders headers, Class<T> responseType) {
        HttpEntity<String> httpEntity = new HttpEntity<>(headers);
        return this.getRestTemplate().postForObject(url, httpEntity, responseType);
    }
}
